import 'package:flutter/material.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../ui.dart';

class UiLifeCycle extends StatefulWidget {
  const UiLifeCycle({
    super.key,
    required this.child,
    this.onLoad,
    this.onShow,
    this.onReady,
    this.onHide,
    this.onRouteDone,
    this.onUnload,
    this.onInactive,
    this.onPaused,
    this.onResumed,
    this.onDetached,
    this.onHidden,
  });
  final Widget child;

  /// 页面加载时触发
  final Function()? onLoad;

  /// 页面显示/切入前台时触发 isFirstShow：是否第一次触发
  final Function(bool isFirstShow)? onShow;

  /// 页面初次渲染完成时触发。一个页面只会调用一次，代表页面已经准备妥当，可以和视图层进行交互
  final Function()? onReady;

  /// 页面隐藏/切入后台时触发
  final Function()? onHide;

  /// 路由动画完成时触发
  final Function()? onRouteDone;

  /// 页面卸载时触发
  final Function()? onUnload;

  /// app失去焦点
  final Function()? onInactive;

  /// app从后台恢复到前台
  final Function()? onResumed;

  /// app进入后台
  final Function()? onPaused;

  /// app委派
  final Function()? onDetached;

  /// app隐藏
  final Function()? onHidden;

  @override
  State<UiLifeCycle> createState() => _UiLifeCycleState();
}

class _UiLifeCycleState extends State<UiLifeCycle> with WidgetsBindingObserver {
  /// 页面过渡动画是否完成
  bool pageAnimateCompleted = false;

  /// 页面KEy
  late Key pageKey;

  /// 是否已显示，防止多次触发onShow事件
  bool isVisible = false;

  /// 是否第一次显示
  bool isFirstShow = true;

  @override
  void initState() {
    /// 页面Key
    pageKey = ValueKey(widget.key ?? GlobalKey());

    /// 触发页面加载事件
    widget.onLoad?.call();

    /// 绑定观察者
    WidgetsBinding.instance.addObserver(this);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      widget.onReady?.call();
    });
    super.initState();
  }

  //监听程序进入前后台的状态改变的方法
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        widget.onResumed?.call();
        break;
      case AppLifecycleState.inactive:
        widget.onInactive?.call();
        break;
      case AppLifecycleState.paused:
        widget.onPaused?.call();
        break;
      case AppLifecycleState.hidden:
        widget.onHidden?.call();
        break;
      case AppLifecycleState.detached:
        widget.onDetached?.call();
        break;
    }
  }

  /// 更新值
  void setValue(Function() fn) {
    if (mounted) {
      setState(fn);
    }
  }

  // 销毁
  @override
  void dispose() {
    /// 页面卸载事件触发
    widget.onUnload?.call();

    /// 移除监听
    VisibilityDetectorController.instance.forget(pageKey);

    /// 移除观察者
    WidgetsBinding.instance.removeObserver(this);

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Ui.onPageAnimateCompleted(context, () {
      if (!pageAnimateCompleted) {
        pageAnimateCompleted = true;
        widget.onRouteDone?.call();
      }
    });

    return VisibilityDetector(
      key: pageKey,
      onVisibilityChanged: (info) {
        if (info.visibleFraction > 0) {
          if (!isVisible) {
            isVisible = true;
            widget.onShow?.call(isFirstShow);
            isFirstShow = false;
          }
        } else if (info.visibleFraction == 0) {
          isVisible = false;
          widget.onHide?.call();
        }
      },
      child: widget.child,
    );
  }
}
